package com.heqiang.es.utils;

import com.heqiang.es.entity.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public class HttpParseUtils {
    public List<Content> parseJD(String keyWords) throws Exception {
        //获取请求 https://search.jd.com/Search?keyword=java
        //前提 需要联网 ajax请求无法获取 获取需要模拟浏览器
        String url = "https://search.jd.com/Search?keyword=" + keyWords;
        //解析网页 (Jsoup返回Document就是浏览器Document对象
        Document document = Jsoup.parse(new URL(url), 30000);
        //所有在js中的使用的方法都阔以用
        Element element = document.getElementById("J_goodsList");
        //获取所有li元素
        Elements elements = element.getElementsByTag("li");
        ArrayList<Content> goodsList = new ArrayList();
        //获取每一个li元素的内容
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            goodsList.add(content);
        }
        return goodsList;
    }

//    public static void main(String[] args) throws IOException {
//        String url = "https://search.jd.com/Search?keyword=java";
//        //解析网页 (Jsoup返回Document就是浏览器Document对象
//        Document document = Jsoup.parse(new URL(url), 30000);
//        //获取所有li元素
//        Element element = document.getElementById("J_goodsList");
//        Elements elements = element.getElementsByTag("li");
//        //获取每一个li元素的内容
//        for (Element el : elements) {
//            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
//            String price = el.getElementsByClass("p-price").eq(0).text();
//            String title = el.getElementsByClass("p-name").eq(0).text();
////            if (StringUtils.isEmpty(img)||StringUtils.isEmpty(price)||StringUtils.isEmpty(Element element = document.getElementById("J_goodsList");title)){
////                continue;
////            }
//            System.out.println(img+price+title);
//            System.out.println("=======================");
//        }
//        System.out.println(elements.size());
//    }

}
